package main;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.android.tpush.XGLocalMessage;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.TimeZone;
import activity.EditCameraActivity;
import activity.FishEye.FishEyeActivity;
import activity.WallMounted.WallMountedActivity;
import activity.addCamera.SelectUseOrNewDeviceActivity;
import activity.live.LiveViewActivity;
import base.HiFragment;
import bean.MyCamera;
import butterknife.BindView;
import butterknife.ButterKnife;
import common.CamHiDefines;
import common.DatabaseManager;
import common.HiDataValue;
import custom.dialog.Effectstype;
import custom.dialog.NiftyDialogBuilder;
import custom.swipelistview.SwipeMenu;
import custom.swipelistview.SwipeMenuCreator;
import custom.swipelistview.SwipeMenuItem;
import main.adapter.CameraListBigAdapter;
import main.adapter.CameraListSmallAdapter;
import utils.HiToast;
import utils.HiTools;
import utils.SharePreUtils;
/**
 * Created by lt on 2017\12\13 0013.
 */
public class CameraFragment extends HiFragment implements View.OnClickListener, ICameraIOSessionCallback, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private View layoutView;
    @BindView(R.id.topButton) ImageView topButton;
    @BindView(R.id.iv_add_camera) ImageView iv_add_camera;
    @BindView(R.id.rl_add_circular) RelativeLayout rl_add_circular;
    @BindView(R.id.iv_show_model) ImageView iv_show_model;
    @BindView(R.id.ll_root) LinearLayout ll_root;
    @BindView(R.id.refreshLayout) SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_add_circular) TextView tv_add_circular;

    private CameraBroadcastReceiver receiver;
    private HiThreadConnect connectThread = null;
    private ListView mListView;
    int ranNum;
    private int[] start;
    private int[] end;
    private boolean mCameraListShowModel = false; // false: 大图模式    true:小图列表模式

    private BaseAdapter mAdapter;
    @BindView(R.id.header) ClassicsHeader header;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (receiver == null) {
            receiver = new CameraBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(HiDataValue.ACTION_CAMERA_INIT_END);
            getActivity().registerReceiver(receiver, filter);
        }
        requestEnd();
    }


    public void requestEnd() {
        // 获取数据完毕，发送广播到CameraFragment界面去刷新adapter
        Intent intent = new Intent();
        intent.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
        getActivity().sendBroadcast(intent);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        layoutView = inflater.inflate(R.layout.fragment_camera, null);
        ButterKnife.bind(this, layoutView);
        initView();
        boolean isHaveVirtual = HiTools.checkDeviceHasNavigationBar(getActivity());
        if (isHaveVirtual) {
            int virtualHei = getBottomKeyboardHeight();
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            params.setMargins(0, 0, 0, virtualHei);
            mRefreshLayout.setLayoutParams(params);
        }
        mRefreshLayout.setEnableLoadMore(false);
        setOnListeners();

        header.setAccentColor(getResources().getColor(R.color.color_theme_blue));

        return layoutView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity().getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                deleteItem.setWidth(HiTools.dip2px(CameraFragment.this.getActivity(), 80));
                deleteItem.setHeight(HiTools.dip2px(CameraFragment.this.getActivity(), 200));
                menu.addMenuItem(deleteItem);
            }
        };
    }

    private void initData() {
        if (HiDataValue.CameraList.size() > 0) {
            rl_add_circular.setVisibility(View.GONE);
            iv_show_model.setVisibility(View.VISIBLE);
            mRefreshLayout.setVisibility(View.VISIBLE);
        } else {
            restoreViewAdd();
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void restoreViewAdd() {
        iv_show_model.setVisibility(View.GONE);
        tv_add_circular.setVisibility(View.VISIBLE);
        rl_add_circular.setVisibility(View.VISIBLE);
        iv_add_camera.setVisibility(View.INVISIBLE);
        mRefreshLayout.setVisibility(View.GONE);
        if (start != null && end != null) {
            rl_add_circular.animate().scaleX(1.0f).scaleY(1.0f).setDuration(500).start();
            rl_add_circular.animate().translationX(0.0f).translationY(0.0f).setDuration(0).start();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        for (MyCamera camera : HiDataValue.CameraList) {
            if (camera != null) {
                camera.registerIOSessionListener(CameraFragment.this);
            }
        }
        requestEnd();//去连接,解决三星手机Vivo手机APP 置于后台很久之后在此打开,摄像机未连接。
        initData();
    }

    private void initView() {
        ranNum = (int) (Math.random() * 10000);
        mListView = layoutView.findViewById(R.id.lv_camera);
        mCameraListShowModel = SharePreUtils.getBoolean(HiDataValue.CACHE, getActivity(), "CameraListShowModel");
        mAdapter = mCameraListShowModel ? new CameraListSmallAdapter(getActivity()) : new CameraListBigAdapter(getActivity());
        iv_show_model.setImageResource(mCameraListShowModel ? R.mipmap.small_map : R.mipmap.big_show_model);
        mListView.setAdapter(mAdapter);
        setThemeColor(R.color.edit_box_bg, R.color.edit_box_bg);

    }


    private void setOnListeners() {
        topButton.setOnClickListener(this);
        iv_add_camera.setOnClickListener(this);
        rl_add_circular.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        iv_show_model.setOnClickListener(this);
        mListView.setOnItemLongClickListener(this);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (connectThread == null) {
                    connectThread = new HiThreadConnect();
                    connectThread.start();
                }
                mRefreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topButton:
                MainActivity activity = (MainActivity) getActivity();
                activity.toggle();
                break;
            case R.id.iv_add_camera:
                Intent intent = new Intent(getActivity(), SelectUseOrNewDeviceActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_add_circular:
                handAddCircularAnim();
                break;
            case R.id.iv_show_model:
                iv_show_model.setImageResource(mCameraListShowModel ? R.mipmap.big_show_model : R.mipmap.small_map);
                if (mCameraListShowModel) {
                    mAdapter = new CameraListBigAdapter(getActivity());
                    mListView.setAdapter(mAdapter);
                } else {
                    mAdapter = new CameraListSmallAdapter(getActivity());
                    mListView.setAdapter(mAdapter);
                }
                mCameraListShowModel = !mCameraListShowModel;
                SharePreUtils.putBoolean(HiDataValue.CACHE, getActivity(), "CameraListShowModel", mCameraListShowModel);
                break;
        }
    }

    private void handAddCircularAnim() {
        tv_add_circular.setVisibility(View.GONE);
        start = new int[2];
        rl_add_circular.getLocationOnScreen(start);

        end = new int[2];
        iv_add_camera.getLocationOnScreen(end);

        AnimatorSet set = new AnimatorSet();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(rl_add_circular, "TranslationX", 0f, (end[0] - start[0] - iv_add_camera.getWidth()));
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(rl_add_circular, "TranslationY", 0f, (end[1] - start[1] - iv_add_camera.getWidth()));
        ObjectAnimator anim3 = ObjectAnimator.ofFloat(rl_add_circular, "ScaleX", 1f, 0f);
        ObjectAnimator anim4 = ObjectAnimator.ofFloat(rl_add_circular, "ScaleY", 1f, 0f);

        set.setDuration(500);
        set.setInterpolator(new LinearInterpolator());
        set.playTogether(anim1, anim2, anim3, anim4);
        set.start();
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                AnimatorSet set = new AnimatorSet();
                iv_add_camera.setVisibility(View.VISIBLE);
                ObjectAnimator anim1 = ObjectAnimator.ofFloat(iv_add_camera, "ScaleX", 0, 1);
                ObjectAnimator anim2 = ObjectAnimator.ofFloat(iv_add_camera, "ScaleY", 0, 1);
                set.setDuration(200);
                set.setInterpolator(new LinearInterpolator());
                set.playTogether(anim1, anim2);
                set.start();
                set.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        Intent intent = new Intent(getActivity(), SelectUseOrNewDeviceActivity.class);
                        startActivity(intent);
                    }
                });
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("ResourceType")
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(HiTools.isFastClick()){
            return;
        }
        View v=view.findViewById(R.id.cardview);
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat( v, "ScaleY", 1f, 0.95f,1f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat( v, "ScaleX", 1f, 0.95f,1f);
        set.playTogether(anim1, anim2);
        set.setInterpolator(new LinearInterpolator());
        set.setDuration(150);
        set.start();
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                handItemClick(view, position);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void handItemClick(View view, int position) {
        final MyCamera selectedCamera = HiDataValue.CameraList.get(position);
        if (selectedCamera.getConnectState() == HiCamera.CAMERA_CONNECTION_STATE_LOGIN&&selectedCamera.isSystemState==0) {
            Bundle extras = new Bundle();
            extras.putString(HiDataValue.EXTRAS_KEY_UID, selectedCamera.getUid());
            Intent intent = new Intent();
            intent.putExtras(extras);
            selectedCamera.isFirstEnterLive = SharePreUtils.getBoolean(HiDataValue.CACHE, getActivity(), selectedCamera.getUid() + "isFirstEnterLive", true);
            if (selectedCamera.isWallMounted) {// 壁装新镜头
                intent.setClass(getActivity(), WallMountedActivity.class);
                startActivity(intent);
            } else if (selectedCamera.isFishEye()) {// 是鱼眼的话 就跳转鱼眼界面
                // 初始化鱼眼顶装和壁装的模式
                int num = SharePreUtils.getInt("mInstallMode", getActivity(), selectedCamera.getUid());
                selectedCamera.mInstallMode = num == -1 ? 0 : num;
                intent.setClass(getActivity(), FishEyeActivity.class);
                startActivity(intent);
            } else {
                //intent.setClass(getActivity(), LiveViewActivity.class);
                intent.setClass(getActivity(), LiveViewActivity.class);
                //转场动画设置
                ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(getActivity(), view.findViewById(R.id.iv_snapshot), "iv");
                startActivity(intent, options.toBundle());
            }
            //startActivity(intent);
            HiDataValue.isOnLiveView = true;
            selectedCamera.setAlarmState(0);
            mAdapter.notifyDataSetChanged();
        } else if (selectedCamera.getConnectState() == HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED) {
            if (HiDataValue.ANDROID_VERSION >= 6 && !HiTools.checkPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                showAlertDialog();
                return;
            }
            selectedCamera.connect();
            selectedCamera.registerIOSessionListener(CameraFragment.this);//必须要调用
            mAdapter.notifyDataSetChanged();
        } else if (selectedCamera.getConnectState() == HiCamera.CAMERA_CONNECTION_STATE_WRONG_PASSWORD) {
            Intent intent = new Intent(getActivity(), EditCameraActivity.class);
            intent.putExtra(HiDataValue.EXTRAS_KEY_UID, selectedCamera.getUid());
            startActivity(intent);
            return;
        } else {
            HiToast.showToast(getActivity(), getString(R.string.click_offline_setting));
            return;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        MyCamera camera = HiDataValue.CameraList.get(position);
        showDeleteCameraDialog(camera, Effectstype.Slidetop);
        return true;
    }


    private class CameraBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(HiDataValue.ACTION_CAMERA_INIT_END)) {
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
                if (intent.getBooleanExtra("mIsAdd", false)) {
                    mListView.smoothScrollToPosition(mAdapter.getCount() - 1);
                }
                if (HiDataValue.ANDROID_VERSION >= 6 && !HiTools.checkPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    return;
                }
                if (connectThread == null) {
                    connectThread = new HiThreadConnect();
                    connectThread.start();
                }
            }
        }
    }

    public class HiThreadConnect extends Thread {
        private int connnum = 0;

        public synchronized void run() {
            for (connnum = 0; connnum < HiDataValue.CameraList.size(); connnum++) {
                MyCamera camera = HiDataValue.CameraList.get(connnum);
                if (camera != null) {
                    if (camera.getConnectState() == HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED) {
                        camera.registerIOSessionListener(CameraFragment.this);
                        camera.connect();
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if (connectThread != null) {
                connectThread = null;
            }
        }
    }

    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        msg.arg1 = i;
        msg.obj = hiCamera;
        mHandler.sendMessage(msg);

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg1 == HiChipDefines.HI_P2P_GET_SNAP && arg3 == 0) {
            MyCamera camera = (MyCamera) arg0;
            if (!camera.reciveBmpBuffer(arg2)) {
                return;
            }
        }
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    private void showDeleteCameraDialog(final MyCamera camera, Effectstype type) {
        final NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(getActivity());
        dialog.withTitle(getString(R.string.tip_reminder)).withMessage(camera.getUid() + "\n" + getString(R.string.tips_msg_delete_camera)).withEffect(type).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                showjuHuaDialog();
                camera.bindPushState(false, bindPushResult);
                SharePreUtils.removeKey(HiDataValue.CACHE, getActivity(), camera.getUid() + "isFirstEnterLive");
                SharePreUtils.putBoolean(HiDataValue.CACHE, getActivity(), "isFirstPbOnline", false);
                SharePreUtils.putBoolean(HiDataValue.CACHE, getActivity(), camera.getUid() + "pb", false);
                sendUnRegister(camera, 0);
                Message msg = mHandler.obtainMessage();
                msg.what = HiDataValue.HANDLE_MESSAGE_DELETE_FILE;
                msg.obj = camera;
                mHandler.sendMessageDelayed(msg, 1000);
            }
        }).show();
    }

    MyCamera.OnBindPushResult bindPushResult = new MyCamera.OnBindPushResult() {
        @Override
        public void onBindSuccess(MyCamera camera) {

            if (!camera.handSubXYZ()) {
                if (camera.handSubWTU()) {
                    camera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS_122);
                }else {
                    camera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS);
                }
            } else {
                camera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS_THERE);
            }
            camera.updateServerInDatabase(getActivity());
            sendServer(camera);
            sendRegisterToken(camera);
        }

        @Override
        public void onBindFail(MyCamera camera) {
        }

        @Override
        public void onUnBindSuccess(MyCamera camera) {
            camera.bindPushState(true, bindPushResult);
        }

        @Override
        public void onUnBindFail(MyCamera camera) {
            // 把SubId存放到sharePrefence
            if (camera.getPushState() > 0) {
                SharePreUtils.putInt("subId", getActivity(), camera.getUid(), camera.getPushState());
            }

        }

    };

    protected void sendServer(MyCamera mCamera) {
        // //测试
        // mCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_ADDRESS_GET, null);
        if (mCamera.getServerData() == null) {
            mCamera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS);
            mCamera.updateServerInDatabase(getActivity());
        }
        if (!mCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_ADDRESS_SET)) {
            return;
        }
        if (mCamera.push != null) {
            byte[] info = CamHiDefines.HI_P2P_ALARM_ADDRESS.parseContent(mCamera.push.getPushServer());
            mCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_ADDRESS_SET, info);
        }
    }

    protected void sendRegisterToken(MyCamera mCamera) {
        if (mCamera.getPushState() == 1 || mCamera.getPushState() == 0) {

            return;
        }

        if (!mCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_TOKEN_REGIST)) {
            return;
        }

        byte[] info = CamHiDefines.HI_P2P_ALARM_TOKEN_INFO.parseContent(0, mCamera.getPushState(), (int) (System.currentTimeMillis() / 1000 / 3600), 1);

        mCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_TOKEN_REGIST, info);
    }

    private void sendUnRegister(MyCamera mCamera, int enable) {
        if (mCamera.getPushState() == 1) {
            return;
        }

        if (!mCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_TOKEN_UNREGIST)) {
            return;
        }

        byte[] info = CamHiDefines.HI_P2P_ALARM_TOKEN_INFO.parseContent(0, mCamera.getPushState(), (int) (System.currentTimeMillis() / 1000 / 3600), enable);
        mCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_TOKEN_UNREGIST, info);
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            MyCamera camera = (MyCamera) msg.obj;
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SESSION_STATE:
                    handSessionState(msg, camera);
                    break;
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {
                        handIOCTRLSucce(msg, camera);
                    } else {// 失败
                        handIOCTRLFail(msg);
                    }
                    break;

                case HiDataValue.HANDLE_MESSAGE_DELETE_FILE:
                    camera.disconnect();
                    camera.deleteInCameraList();
                    camera.deleteInDatabase(getActivity());
                    mAdapter.notifyDataSetChanged();
                    dismissjuHuaDialog();
                    HiToast.showToast(getActivity(), getString(R.string.tips_remove_success));
                    if (HiDataValue.CameraList.size() < 1) {
                        restoreViewAdd();
                    }
                    break;
            }
        }

        private void handIOCTRLSucce(Message msg, MyCamera camera) {
            Bundle bundle = msg.getData();
            byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
            switch (msg.arg1) {
                case HiChipDefines.HI_P2P_GET_SNAP:
                    mAdapter.notifyDataSetChanged();
                    if (camera.snapshot != null) {
                        File rootFolder = new File(getContext().getFilesDir().getAbsolutePath() + "/");
                        File sargetFolder = new File(rootFolder.getAbsolutePath() + "/android/data/" + getActivity().getResources().getString(R.string.app_name));
                        if (!rootFolder.exists()) {
                            rootFolder.mkdirs();
                        }
                        if (!sargetFolder.exists()) {
                            sargetFolder.mkdirs();
                        }
                    }
                    break;

                case HiChipDefines.HI_P2P_GET_TIME_ZONE: {
                    HiChipDefines.HI_P2P_S_TIME_ZONE timezone = new HiChipDefines.HI_P2P_S_TIME_ZONE(data);
                    if (timezone.u32DstMode == 1) {
                        camera.setSummerTimer(true);
                    } else {
                        camera.setSummerTimer(false);
                    }
                }
                break;
                case HiChipDefines.HI_P2P_GET_TIME_ZONE_EXT: {
                    HiChipDefines.HI_P2P_S_TIME_ZONE_EXT timezone = new HiChipDefines.HI_P2P_S_TIME_ZONE_EXT(data);
                    if (timezone.u32DstMode == 1) {
                        camera.setSummerTimer(true);
                    } else {
                        camera.setSummerTimer(false);
                    }
                    break;
                }
                case CamHiDefines.HI_P2P_ALARM_TOKEN_REGIST:

                    break;
                case CamHiDefines.HI_P2P_ALARM_TOKEN_UNREGIST:
                    break;
                case CamHiDefines.HI_P2P_ALARM_ADDRESS_SET:
                    break;
                case CamHiDefines.HI_P2P_ALARM_ADDRESS_GET:
                    break;

                // 服务器直推的回调
                case HiChipDefines.HI_P2P_ALARM_EVENT: {
                    if (camera.getPushState() == 0) {
                        return;
                    }
                    /*
                     * //相对摄像机时间的每30秒一次回调， if(System.currentTimeMillis() - camera.getLastAlarmTime() < 30000) { HiLog.e("Time lastAlarmTime:"+(System. currentTimeMillis() - lastAlarmTime)); return; }
                     */
                    camera.setLastAlarmTime(System.currentTimeMillis());
                    HiChipDefines.HI_P2P_EVENT event = new HiChipDefines.HI_P2P_EVENT(data);
                    //showAlarmNotification(camera, event, System.currentTimeMillis());

                    XGLocalMessage local_msg=new XGLocalMessage();
                    local_msg.setTitle(camera.getUid());
                    //设置本地消息类型，1:通知，2:消息
                    local_msg.setType(1);
                    String type=handNotiContentType(event);
                    local_msg.setContent(type);
                    local_msg.setAction_type(1);
                    local_msg.setActivity("main.MainActivity");
                    XGPushManager.addLocalNotification(getContext(),local_msg);

                    saveAlarmData(camera, event.u32Event, (int) (System.currentTimeMillis() / 1000));
                    camera.setAlarmState(1);
                    camera.setAlarmLog(true);
                    mAdapter.notifyDataSetChanged();
                }
                break;
                case HiChipDefines.HI_P2P_GET_DEVICE_FISH_PARAM:
                    HiChipDefines.HI_P2P_DEV_FISH fishmod = new HiChipDefines.HI_P2P_DEV_FISH(data);
                    float xcircle = fishmod.xcircle;
                    float ycircle = fishmod.ycircle;
                    float rcircle = fishmod.rcircle;

                    SharePreUtils.putFloat(HiDataValue.CACHE, getContext(), camera.getUid() + "xcircle", xcircle);
                    SharePreUtils.putFloat(HiDataValue.CACHE, getContext(), camera.getUid() + "ycircle", ycircle);
                    SharePreUtils.putFloat(HiDataValue.CACHE, getContext(), camera.getUid() + "rcircle", rcircle);
                    SharePreUtils.putInt("mInstallMode", getContext(), camera.getUid(), fishmod.mold);
                    if (fishmod.fish == 1 && (fishmod.type == 2||fishmod.type == 4)) {//fishmod==2 fishmod==4 都是广角
                        camera.isWallMounted = true;
                        SharePreUtils.putBoolean(HiDataValue.CACHE, getActivity(), camera.getUid() + "isWallMounted", true);
                    }
                    camera.putFishModType(fishmod.type);
                    break;
                case HiChipDefines.HI_P2P_GET_RESOLUTION:
                    HiChipDefines.HI_P2P_RESOLUTION param = new HiChipDefines.HI_P2P_RESOLUTION(data);
                    camera.u32Resolution = param.u32Resolution;
                    break;
            }
        }
    };

    private String  handNotiContentType(HiChipDefines.HI_P2P_EVENT event) {
        String[] alarmList = getResources().getStringArray(R.array.tips_alarm_list_array);
        String type = null;
        switch (event.u32Event) {
            case 0:
                type = alarmList[0];
                break;
            case 1:
                type = alarmList[1];
                break;
            case 2:
                type = alarmList[2];
                break;
            case 3:
                type = alarmList[3];
                break;
            case 6:
                String sType = new String(event.sType).trim();
                if ("key2".equals(sType)) {
                    type = getString(R.string.alarm_sos);
                } else if ("key3".equals(sType)) {
                    type = getString(R.string.alarm_ring);
                } else if ("door".equals(sType)) {
                    type = getString(R.string.alarm_door);
                } else if ("infra".equals(sType)) {
                    type = getString(R.string.alarm_infra);
                } else if ("beep".equals(sType)) {
                    type = getString(R.string.alarm_doorbell);
                } else if ("fire".equals(sType)) {
                    type = getString(R.string.alarm_smoke);
                } else if ("gas".equals(sType)) {
                    type = getString(R.string.alarm_gas);
                } else if ("socket".equals(sType)) {
                    type = getString(R.string.alarm_socket);
                } else if ("temp".equals(sType)) {
                    type = getString(R.string.alarm_temp);
                } else if ("humi".equals(sType)) {
                    type = getString(R.string.alarm_humi);
                }
                break;
        }
        return  type;
    }

    private void handIOCTRLFail(Message msg) {
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_GET_SNAP:
                break;

        }
    }

    private void handSessionState(Message msg, MyCamera camera) {
        if (mAdapter != null) {
            camera.isSystemState = 0;// 必须要在更新之前回置成0
            mAdapter.notifyDataSetChanged();
        }
        switch (msg.arg1) {
            case HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED:
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_LOGIN:
                camera.setReconnectTimes(10);
                if (camera.getCommandFunction(HiChipDefines.HI_P2P_SET_MD_PARAM_NEW)) {
                    camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_RESOLUTION, HiChipDefines.HI_P2P_RESOLUTION.parseContent(0, 1));
                }
                setTime(camera);
                if (camera.getPushState() > 0) {
                    camera.bindPushState(true, bindPushResult);
                    setServer(camera);
                }
                if (!camera.getCommandFunction(HiChipDefines.HI_P2P_PB_QUERY_START_NODST)) {
                    if (camera.getCommandFunction(HiChipDefines.HI_P2P_GET_TIME_ZONE_EXT)) {
                        camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_TIME_ZONE_EXT, new byte[0]);
                    } else {
                        camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_TIME_ZONE, new byte[0]);
                    }
                }
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_WRONG_PASSWORD:
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_CONNECTING:
                break;
        }
    }

    // 报警推送到通知栏 ****API 11及之后可用****
    @SuppressWarnings("deprecation")
    private void showAlarmNotification(MyCamera camera, HiChipDefines.HI_P2P_EVENT event, long evtTime) {
        try {
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
            Bundle extras = new Bundle();
            extras.putString(HiDataValue.EXTRAS_KEY_UID, camera.getUid());
            extras.putInt("type", 1);
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.putExtras(extras);
            PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            String[] alarmList = getResources().getStringArray(R.array.tips_alarm_list_array);
            String type = null;
            switch (event.u32Event) {
                case 0:
                    type = alarmList[0];
                    break;
                case 1:
                    type = alarmList[1];
                    break;
                case 2:
                    type = alarmList[2];
                    break;
                case 3:
                    type = alarmList[3];
                    break;
                case 6:
                    String sType = new String(event.sType).trim();
                    if ("key2".equals(sType)) {
                        type = getString(R.string.alarm_sos);
                    } else if ("key3".equals(sType)) {
                        type = getString(R.string.alarm_ring);
                    } else if ("door".equals(sType)) {
                        type = getString(R.string.alarm_door);
                    } else if ("infra".equals(sType)) {
                        type = getString(R.string.alarm_infra);
                    } else if ("beep".equals(sType)) {
                        type = getString(R.string.alarm_doorbell);
                    } else if ("fire".equals(sType)) {
                        type = getString(R.string.alarm_smoke);
                    } else if ("gas".equals(sType)) {
                        type = getString(R.string.alarm_gas);
                    } else if ("socket".equals(sType)) {
                        type = getString(R.string.alarm_socket);
                    } else if ("temp".equals(sType)) {
                        type = getString(R.string.alarm_temp);
                    } else if ("humi".equals(sType)) {
                        type = getString(R.string.alarm_humi);
                    }
                    break;
            }
            Notification notification = new Notification.Builder(getActivity()).setSmallIcon(R.mipmap.ic_launcher).setTicker(camera.getNikeName()).setContentTitle(camera.getUid()).setContentText(type).setContentIntent(pendingIntent).getNotification();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.defaults = Notification.DEFAULT_ALL;
            ranNum++;
            manager.notify(ranNum, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void saveAlarmData(MyCamera camera, int evtType, int evtTime) {

        DatabaseManager manager = new DatabaseManager(getActivity());
        manager.addAlarmEvent(camera.getUid(), evtTime, evtType);

    }


    private void setTime(MyCamera camera) {
        Calendar cal = Calendar.getInstance(TimeZone.getDefault());
        cal.setTimeInMillis(System.currentTimeMillis());

        byte[] time = HiChipDefines.HI_P2P_S_TIME_PARAM.parseContent(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));

        camera.sendIOCtrl(HiChipDefines.HI_P2P_SET_TIME_PARAM, time);
    }

    protected void setServer(MyCamera mCamera) {
        if (!mCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_ADDRESS_SET)) {
            return;
        }
        // 如果数据库保存的还是老地址就解绑并绑定新的地址
        if (mCamera.getServerData() != null && !mCamera.getServerData().equals(HiDataValue.CAMERA_ALARM_ADDRESS)) {
            if (mCamera.getPushState() > 1) {
                if (HiDataValue.XGToken == null) {
                    if (HiDataValue.ANDROID_VERSION >= 6) {
                        if (!HiTools.checkPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                        }
                    }

                    HiDataValue.XGToken = XGPushConfig.getToken(getActivity());
                }
                mCamera.bindPushState(false, bindPushResult);
                return;
            }
        }
        sendServer(mCamera);
        sendRegisterToken(mCamera);

    }

    private void setThemeColor(int colorPrimary, int colorPrimaryDark) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.white);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(receiver);
        if (connectThread != null) {
            connectThread.interrupt();
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        getActivity().overridePendingTransition(R.anim.in_act_my, R.anim.out_act_my);
    }

    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        super.startActivity(intent, options);
    }

    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getString(R.string.tips_no_permission));
        builder.setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                HiTools.toSelfSetting(getContext());
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), null);
        builder.setCancelable(false);
        builder.show();

    }

        /**
         * 获取底部虚拟键盘的高度
         */
    public int getBottomKeyboardHeight() {
        int screenHeight = getAccurateScreenDpi()[1];
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int heightDifference = screenHeight - dm.heightPixels;
        return heightDifference;
    }

    /**
     * 获取精确的屏幕大小
     */
    public int[] getAccurateScreenDpi() {
        int[] screenWH = new int[2];
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        try {
            Class<?> c = Class.forName("android.view.Display");
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            screenWH[0] = dm.widthPixels;
            screenWH[1] = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenWH;
    }

}







